package edu.zut.main.socket;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;

public class SocketDemo1 {

}

//模拟客户端发送信息给服务器     一对一 单一通信
//一对一  交互通信  while  直到一方说再见 再断开连接
//一对多   多个客户端  一个服务器  通信   + 线程控制   参考：抢票
//客户端
class Client{

    public static void main(String[] args) throws IOException {
        //创建一个套接字对象  基于ip+port
        InetAddress inetAddress = InetAddress.getByName("127.0.0.1");
        Socket socket = new Socket(inetAddress, 9999);

        System.out.println("客户端连接成功");
        //获取一个输出流
        OutputStream outputStream = socket.getOutputStream();
        outputStream.write("hello,我是客户端".getBytes());

        //关闭客户端的输出流
        socket.shutdownOutput();

        //接收服务器返回的信息
        InputStream is = socket.getInputStream();
        byte[] buffer = new byte[1024];
        int len;
        while ((len = is.read(buffer)) != -1){
            System.out.println(new String(buffer,0,len));
        }
        //关闭资源
        is.close();
        outputStream.close();
        socket.close();
    }

}


//服务器
class Server{

    public static void main(String[] args) throws IOException {
        //实例化一个服务器   同时制定端口号
        ServerSocket server = new ServerSocket(9999);
        System.out.println("等待客户端连接");
        //服务器要监听客户端的请求  accept
        Socket socket = server.accept();
        System.out.println("连接已成功");
        //服务器要接收客户端发送的数据
        InputStream is = socket.getInputStream();
        byte[] buffer = new byte[1024];
        int i = is.read(buffer);
        while (i != -1){
            System.out.println(new String(buffer,0,i));
            i = is.read(buffer);
        }

        //关闭输入流
        socket.shutdownInput();

        //服务器也可以返回消息给客户端
        OutputStream os = socket.getOutputStream();
        os.write("hello,我是服务器!!!!".getBytes());

        //关闭资源
        os.close();
        is.close();
        server.close();

    }
}